package cn.utry.sipGateWay.tcpdump;

import java.io.IOException;
import java.net.InetAddress;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import jpcap.JpcapCaptor;
import jpcap.NetworkInterface;
import jpcap.NetworkInterfaceAddress;

public class WireShark {
	private static final Logger log = LoggerFactory.getLogger(WireShark.class);

	public static void start(int index) {
		log.info("获取网卡信息。。。。。。。。。");
		NetworkInterface networkInterface = getNetworkInterface(index);
		log.info("开始抓取网卡{} {} {} 的数据", networkInterface.name, networkInterface.description,getIps(networkInterface.addresses));
		int caplen = 1512;
		boolean promiscCheck = true;
		try {
			JpcapCaptor jpcap = JpcapCaptor.openDevice(networkInterface, caplen, promiscCheck, 50);
			Receiver reciver = new Receiver();
			reciver.setFilter(new Filter());
			jpcap.loopPacket(-1, reciver);

		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	public static NetworkInterface getNetworkInterface(int index) {
		/*--------------	第一步绑定网络设备       --------------*/
		NetworkInterface[] devices = JpcapCaptor.getDeviceList();

		for (NetworkInterface n : devices) {
			log.info("网卡名称:{}   网卡说明:{} ", n.name, n.description);
		}
		if (index > devices.length) {
			return null;
		} else {
			return devices[index];
		}
	}

	public static String getIps(NetworkInterfaceAddress[] address) {
		StringBuffer str = new StringBuffer("");
		InetAddress inetAddress = address[address.length-1].address;
		if (inetAddress != null) {
			str.append(inetAddress.getHostAddress());
		}
		return str.toString();
	}
}
